<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="../js/babel.js"></script>
</head>

<body>
  <div id="root"></div>
</body>

</html>

<script type="text/babel">
  // 非受控组件: 页面中所有输入类的dom 现用现取
  class Login extends React.Component {
    handleSubmit = (e) => {
      e.preventDefault() // 阻止默认行为 防止表单默认跳转-页面刷新
      const { username, password } = this
      alert(`用户名: ${username.value}, 密码: ${password}`)
    }
    render() {
      return (
        <form onSubmit={this.handleSubmit}>
          <label>
            用户名
            <input type="text" ref={(c) => this.username = c} name='username' />
          </label>
          <label>
            密码
            <input type="password" ref={c => this.password = c} name='password' />

          </label>
          <button>登录</button>
        </form>)
    }
  }

  // 受控组件 页面中的所有输入类的dom 随着你的输入 维护状态 就是受控组件   建议使用受控组件
  class Login2 extends React.Component {
    state = {
      userInfo: {
        username: '',
        password: ''
      }
    }

    handleSubmit = (e) => {
      e.preventDefault()
      const { username, password } = this.state.userInfo
      alert(`用户名: ${username}, 密码: ${password}`)
    }

    handleUsername = (e) => {
      this.setState({
        userInfo: {
          ...this.state.userInfo,
          username: e.target.value
        }

      })
    }

    handlePassword = (e) => {
      this.setState({
        userInfo: {
          ...this.state.userInfo,
          password: e.target.value
        }
      })
    }

    render() {
      return (
        <form onSubmit={this.handleSubmit}>
          <label>
            用户名
            <input type="text" name='username' onChange={this.handleUsername} />
          </label>
          <label>
            密码
            <input type="text" name='password' onChange={this.handlePassword} />
          </label>
          <button>登录</button>
        </form>
      )
    }
  }

  ReactDOM.render(<Login2 />, document.getElementById('root'))
</script>